package cn.codeant.aircrack.ui;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.Nullable;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.codeant.aircrack.R;
import cn.codeant.aircrack.utils.AssetUtils;

public class MainActivity extends Activity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    private static final String CRACK_BIN = "aircrack-ng";

    private TextView msgTv;
    private Button startBtn;

    private Handler handler = new Handler();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        msgTv = findViewById(R.id.tv_main_msg);
        startBtn = findViewById(R.id.btn_main_start);
        startBtn.setOnClickListener(this);
    }

    private void crackStart(){
        startBtn.setEnabled(false);

        final int keyTotal = 9000;
        final Pattern testedPattern = Pattern.compile(".*\\[(\\d*:\\d*:\\d*)]\\s(.*)/.*keys tested\\s\\((.*)\\).*");
        final Pattern keyPattern = Pattern.compile(".*\\[2KKEY FOUND!\\s\\[\\s(.*)\\s].*");

        new Thread(){
            @Override
            public void run() {
                String bin = new File(getDir("bin", Context.MODE_PRIVATE),CRACK_BIN)
                        .getAbsolutePath();
                String dict = new File(getFilesDir(),"GoldDictionary.dict").getAbsolutePath();
                String handshake = new File(getFilesDir(),"A86B7C44AA7B-handshake.pcap").getAbsolutePath();
                String apMac = "A8:6B:7C:44:AA:7B";

                if(!AssetUtils.copyFileOverwrite(MainActivity.this,CRACK_BIN,bin)){
                    crackEnd("aircrack-ng工具拷贝错误");
                    return;
                }
                AssetUtils.copyFileOverwrite(MainActivity.this,"GoldDictionary.dict",dict);
                AssetUtils.copyFileOverwrite(MainActivity.this,"A86B7C44AA7B-handshake.pcap",handshake);

                String cmd = "chmod +x "+bin+"\n" // 添加权限
                           + bin + " -a 2 -b " + apMac + " -p 4 -w " + dict + " " + handshake;

                Process process = null;
                try {
                    String libDir = getFilesDir().getParent() + "/lib";
                    process = Runtime.getRuntime().exec(new String[]{"sh", "-c", cmd},
                            new String[]{"LD_LIBRARY_PATH=" + libDir + ":$LD_LIBRARY_PATH"});
                    BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    String line;
                    while ((line = br.readLine())!=null){
                        Log.d(TAG,line);

                        if (line.contains("keys tested")) {
                            Matcher matcher = testedPattern.matcher(line);
                            if (matcher.find()) {
                                String usedTimeStr = matcher.group(1); // 表示第一个括号里的东西
                                String keysStr = matcher.group(2);     // 表示第二个括号里的东西
                                String keySpeed = matcher.group(3);     // 表示第三个括号里的东西

                                postMsg(String.format(Locale.getDefault(),
                                        "尝试： [%s]%5s/%d (%s)",usedTimeStr,keysStr,keyTotal,keySpeed));
                            }
                        } else if (line.contains("KEY FOUND")) {
                            Matcher matcher = keyPattern.matcher(line);
                            if (matcher.find()) {
                                crackEnd("破解成功： "+matcher.group(1));
                                return;
                            }
                        }
                    }

                    br = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                    while ((line = br.readLine())!=null) {
                        Log.d(TAG, line);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    postMsg("执行错误： "+e.getMessage());
                }

                if(null!=process)
                    process.destroy();

                crackEnd("破解失败： 未匹配到密码");
            }
        }.start();
    }

    private void crackEnd(final String msg){
        handler.post(new Runnable() {
            @Override
            public void run() {
                msgTv.setText(msg);
                startBtn.setEnabled(true);
            }
        });
    }

    private void postMsg(final String msg){
        handler.post(new Runnable() {
            @Override
            public void run() {
                msgTv.setText(msg);
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_main_start:
                crackStart();
                break;
            default:
                break;
        }
    }
}
